<template>
  <div class="login-container">
    <div class="login-form">
      <img class="left-img" :src="leftImg" />
      <el-form ref="formRef" label-position="left" :model="form" :rules="rules">
        <div class="title">Hello !</div>
        <div class="title-tips">
          {{ translateTitle('欢迎来到') }}{{ title }}！
        </div>
        <el-form-item prop="username">
          <el-input
            v-focus
            type="text"
            tabindex="1"
            v-model.trim="form.username"
            :placeholder="translateTitle('请输入用户名')"
          >
            <template #prefix>
              <vab-icon icon="user-line" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            tabindex="2"
            :key="passwordType"
            type="password"
            ref="passwordRef"
            @keyup.enter="handleLogin"
            v-model.trim="form.password"
            :placeholder="translateTitle('请输入密码')"
          >
            <template #prefix>
              <vab-icon icon="lock-line" />
            </template>
          </el-input>
        </el-form-item>
        <!-- 验证码验证逻辑需自行开发，如不需要验证码功能建议注释 -->
        <el-form-item prop="verificationCode">
          <el-input
            type="text"
            tabindex="3"
            v-model.trim="form.verificationCode"
            :placeholder="translateTitle('验证码') + previewText"
          >
            <template #prefix>
              <vab-icon icon="barcode-box-line" />
            </template>
          </el-input>
          <el-image class="code" :src="codeUrl" @click="changeCode" />
        </el-form-item>
        <el-button class="login-btn" type="primary" @click="handleLogin">
          {{ translateTitle('登录') }}
        </el-button>
        <!-- <router-link :to="`/resetPwd?username=${form.username}`">
          <el-button style="margin-top: 20px; margin-left: -10px">
            {{ translateTitle('重置密码') }}
          </el-button>
        </router-link> -->
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { useSettingsStore } from '/@/store/modules/settings'
  import { useUserStore } from '/@/store/modules/user'
  import { translateTitle } from '/@/utils/i18n'
  import { isPassword } from '/@/utils/validate'
  import { onBeforeRouteLeave } from 'vue-router'

  import { getImageUrl } from '/@/utils/imageUrl'

  defineOptions({
    name: 'Login',
  })

  const route = useRoute()
  const router = useRouter()

  const userStore = useUserStore()
  const settingsStore = useSettingsStore()

  const leftImg = ref('')
  const img = getImageUrl(`assets/login_images/left_img.png`)
  leftImg.value = img

  const login = (form: any) => userStore.login(form)

  const validateUsername = (rule: any, value: any, callback: any) => {
    if ('' === value) callback(new Error(translateTitle('用户名不能为空')))
    else callback()
  }
  const validatePassword = (rule: any, value: any, callback: any) => {
    if (!isPassword(value))
      callback(new Error(translateTitle('密码不能少于6位')))
    else callback()
  }

  const title = settingsStore.getTitle

  const formRef: Ref<any> = ref(null)
  const passwordRef: Ref<any> = ref(null)

  const form = reactive({
    username: 'CUST0043',
    password: '888888',
    verificationCode: '',
  })

  const rules: any = reactive({
    username: [
      {
        required: true,
        trigger: 'blur',
        validator: validateUsername,
      },
    ],
    password: [
      {
        required: true,
        trigger: 'blur',
        validator: validatePassword,
      },
    ],
  })

  const loading: Ref<any> = ref(false)
  const passwordType: Ref<any> = ref('password')
  const redirect: Ref<any> = ref(undefined)
  const timer: Ref<any> = ref(0)
  const codeUrl: Ref<any> = ref('https://www.oschina.net/action/user/captcha')
  const previewText: Ref<any> = ref('')

  const handleRoute = () => {
    return redirect.value === '/404' || redirect.value === '/403'
      ? '/'
      : redirect.value
  }

  document.onkeydown = function (event) {
    if (event.key == 'Enter') {
      handleLogin()
    }
  }

  const handleLogin = async () => {
    formRef.value.validate(async (valid: any) => {
      if (valid)
        try {
          loading.value = true
          await login({
            account: form.username,
            pwd: form.password,
          }).catch(() => {})
          await router.push(handleRoute())
        } finally {
          loading.value = false
        }
    })
  }
  const changeCode = () => {
    codeUrl.value = `https://www.oschina.net/action/user/captcha?timestamp=${new Date().getTime()}`
  }

  onBeforeMount(() => {
    // form.username = 'admin'
    // form.password = '123456'
    // // 为了演示效果，会在官网演示页自动登录到首页，正式开发可删除
    // if (
    //   location.hostname === 'vue-admin-beautiful.com' ||
    //   location.hostname === 'chu1204505056.gitee.io'
    // ) {
    //   previewText.value = '（演示地址验证码可不填）'
    //   timer.value = setTimeout(() => {
    //     handleLogin()
    //   }, 5000)
    // }
  })

  watchEffect(() => {
    redirect.value = (route.query && route.query.redirect) || '/'
  })

  onBeforeRouteLeave((to, from, next) => {
    clearInterval(timer.value)
    next()
  })
</script>

<style lang="scss" scoped>
  .login-container {
    position: relative;
    height: 100vh;
    padding-top: 20vh;
    background: url('/@/assets/login_images/background.jpg') center center fixed
      no-repeat;
    background-size: cover;
  }

  @media (max-width: 576px) {
    .login-form {
      width: 85vw !important;
      margin: auto !important;

      .left-img {
        display: none !important;
      }

      :deep() {
        .el-form--default {
          width: 94% !important;
        }
      }
    }
  }

  .login-form {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    width: 1000px;
    height: 550px;
    padding: 4.5vh;
    margin: auto;
    overflow: hidden;
    background: var(--el-color-white);
    background-size: 100% 100%;
    border-radius: 15px;

    .left-img {
      float: left;
      width: 50%;
    }

    :deep() {
      .el-form--default {
        float: left;
        width: 44%;
        margin-left: 5.8%;
      }

      .el-input__wrapper {
        height: auto;
      }

      .title {
        font-size: 54px;
        font-weight: 500;
        color: var(--el-color-black);
      }

      .title-tips {
        margin-top: 29px;
        font-size: 26px;
        font-weight: 400;
        color: var(--el-color-black);
      }

      .login-btn {
        display: inherit;
        width: 100%;
        height: 50px;
        margin-top: 15px;
        border: 0;

        &:hover {
          opacity: 0.9;
        }

        .forget-passwordword {
          width: 100%;
          margin-top: 40px;
          text-align: left;

          .forget-password {
            width: 129px;
            height: 19px;
            font-size: 20px;
            font-weight: 400;
            color: rgba(92, 102, 240, 1);
          }
        }
      }

      .tips {
        margin-bottom: 10px;
        font-size: var(--el-font-size-default);
        color: var(--el-color-white);

        span {
          &:first-of-type {
            margin-right: 16px;
          }
        }
      }

      .title-container {
        position: relative;

        .title {
          margin: 0 auto 40px auto;
          font-size: 34px;
          font-weight: bold;
          color: var(--el-color-primary);
          text-align: center;
        }
      }

      i {
        position: absolute;
        top: 9px;
        left: 15px;
        z-index: $base-z-index;
        font-size: 16px;
        color: var(--el-color-black);
        cursor: pointer;
        user-select: none;
      }

      .show-password {
        position: absolute;
        right: 25px;
        left: -35px;
        font-size: 16px;
        color: var(--el-color-black);
        cursor: pointer;
        user-select: none;
      }

      .el-form-item {
        padding-right: 0;
        margin: 20px 0;
        color: #454545;
        background: transparent;
        border: 1px solid transparent;
        border-radius: 2px;

        &__content {
          min-height: $base-input-height;
          line-height: $base-input-height;
        }

        &__error {
          position: absolute;
          top: 100%;
          left: 18px;
          font-size: var(--el-font-size-small);
          line-height: 18px;
          color: var(--el-color-error);
        }
      }

      .el-input {
        box-sizing: border-box;

        input {
          height: 48px;
          padding-left: 35px;
          font-size: var(--el-font-size-default);
          line-height: 48px;
          background: var(--el-color-white);
          border: 0;
        }
      }

      .code {
        position: absolute;
        top: 4px;
        right: 4px;
        cursor: pointer;
        border-radius: var(--el-border-radius-base);
      }
    }
  }
</style>
